package com.online.college.portal.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.egzosn.pay.ali.api.AliPayConfigStorage;
import com.egzosn.pay.ali.api.AliPayService;
import com.egzosn.pay.ali.bean.AliTransactionType;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.MethodType;
import com.egzosn.pay.common.bean.PayOrder;
import com.egzosn.pay.common.http.HttpConfigStorage;
import com.egzosn.pay.wx.api.WxPayConfigStorage;
import com.egzosn.pay.wx.api.WxPayService;
import com.egzosn.pay.wx.bean.WxTransactionType;
import com.online.college.common.pay.AliPayConfig;
import com.online.college.common.pay.WxPayConfig;
import com.online.college.common.util.*;
import com.online.college.core.message.domain.Message;
import com.online.college.core.message.domain.MessageText;
import com.online.college.core.message.service.IMessageService;
import com.online.college.core.message.service.IMessageTextService;
import com.online.college.core.pay.domain.PayOrders;
import freemarker.log.Logger;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.online.college.common.page.TailPage;
import com.online.college.common.storage.QiniuStorage;
import com.online.college.common.util.EncryptUtil;
import com.online.college.common.web.JsonView;
import com.online.college.common.web.SessionContext;
import com.online.college.core.auth.domain.AuthUser;
import com.online.college.core.auth.service.IAuthUserService;
import com.online.college.core.course.domain.CourseComment;
import com.online.college.core.course.service.ICourseCommentService;
import com.online.college.core.user.domain.UserCollections;
import com.online.college.core.user.domain.UserCourseSection;
import com.online.college.core.user.domain.UserCourseSectionDto;
import com.online.college.core.user.domain.UserFollowStudyRecord;
import com.online.college.core.user.service.IUserCollectionsService;
import com.online.college.core.user.service.IUserCourseSectionService;
import com.online.college.core.user.service.IUserFollowsService;

@Controller
@RequestMapping("/user")
public class UserController {
    static final Logger log = Logger.getLogger("UserController");
	@Autowired
	private IUserFollowsService userFollowsService;
	
	@Autowired
	private IAuthUserService authUserService;

	@Autowired
	private IMessageService messageService;

	@Autowired
    private IMessageTextService messageTextService;
	
	@Autowired
	private IUserCourseSectionService userCourseSectionService;
	
	@Autowired
	private IUserCollectionsService userCollectionsService;
	
	@Autowired
	private ICourseCommentService courseCommentService;

	/**
	 * ‘我的’-》动态圈
	 * @param page
	 * @return
	 */
	@RequestMapping("/home")
	public ModelAndView index(TailPage<UserFollowStudyRecord> page){
		ModelAndView mv = new ModelAndView("user/home"); // 设置这个方法返回的视图  user/home


		mv.addObject("curNav","home");  // 设置属性用于请求传值
		
		//加载关注用户的动态
		UserFollowStudyRecord queryEntity = new UserFollowStudyRecord();
		queryEntity.setUserId(SessionContext.getUserId());
		page = userFollowsService.queryUserFollowStudyRecordPage(queryEntity, page);
		
		//处理用户头像
		for(UserFollowStudyRecord item : page.getItems()){
			if(StringUtils.isNotEmpty(item.getHeader())){
				item.setHeader(QiniuStorage.getUrl(item.getHeader()));
			}
		}
		mv.addObject("page", page);
		
		return mv;
	}

	/**
	 * ‘我的’-》我的课程
	 * @param page
	 * @return
	 */
	@RequestMapping("/mycourse")
	public ModelAndView mycourse(TailPage<UserCourseSectionDto> page){
		ModelAndView mv = new ModelAndView("user/mycourse"); // 设置这个方法返回的视图  user/mycourse
		mv.addObject("curNav","mycourse");  // 设置属性用于请求传值

		//加载我的课程
		UserCourseSection queryEntity = new UserCourseSection();
		queryEntity.setUserId(SessionContext.getUserId());
		page = userCourseSectionService.queryPage(queryEntity, page);

		UserCourseSectionDto ucs = new UserCourseSectionDto();
		if(page.getItems().iterator() != null){
			for(int i=0;i<page.getItems().size();i++){
				ucs = page.getItems().get(i);

				long nd = 1000 * 24 * 60 * 60;
				long nh = 1000 * 60 * 60;
				long nm = 1000 * 60;
				long diff = ucs.getUpdateTime().getTime()-ucs.getCreateTime().getTime();
				long day = diff / nd;// 计算差多少天
				long hour = diff % nd / nh;// 计算差多少小时
				long min = diff % nd % nh / nm;// 计算差多少分钟
				// long sec = diff % nd % nh % nm / ns;// 计算差多少秒
				page.getItems().get(i).setTotalLearnTime(day + "天" + hour + "小时" + min + "分");
			}
		}

		System.out.println("我是查出来的数据"+ ucs.getTotalLearnTime());
		mv.addObject("page", page);
		return mv;
	}

	/**
	 * ‘我的’-》修改密码
	 * @param page
	 * @return
	 */
	@RequestMapping("/changepwd")
	public ModelAndView changepwd(TailPage<UserFollowStudyRecord> page){
		ModelAndView mv = new ModelAndView("user/changepwd"); // 设置这个方法返回的视图  user/home


		mv.addObject("curNav","changepwd");  // 设置属性用于请求传值

		//加载关注用户的动态
		UserFollowStudyRecord queryEntity = new UserFollowStudyRecord();
		queryEntity.setUserId(SessionContext.getUserId());
		page = userFollowsService.queryUserFollowStudyRecordPage(queryEntity, page);

		mv.addObject("page", page);

		return mv;
	}

	/**
	 * 我的通知
	 */
	@RequestMapping("/notice")
	public ModelAndView notice(TailPage<MessageText> page){
		ModelAndView mv = new ModelAndView("user/notice");
		mv.addObject("curNav","notice");

		try{
			page = messageTextService.queryListByUserId(SessionContext.getUserId(),page);
			mv.addObject("page",page);
		}catch (Exception e){
			e.printStackTrace();
		}
		return mv;
	}
	/**
	 * 消息设为已读
	 */
	@RequestMapping("/readNotice")
	@ResponseBody
	public String readNotice(Long id){
		try{
			MessageText messageText = new MessageText();
			messageText.setId(id);
			messageText.setMemberId(SessionContext.getUserId());
			messageText.setReadStatus(new Long(1));
			messageTextService.updateSelectivity(messageText);
			return new JsonView(0).toString();//成功
		}catch (Exception e){
			e.printStackTrace();
			return new JsonView(1).toString();//异常
		}
	}

	/**
	 * 消息全部设为已读
	 */
	@RequestMapping("/readNoticeALL")
	public ModelAndView readNoticeAll(TailPage<MessageText> page){
		ModelAndView mv = new ModelAndView("user/notice");
		mv.addObject("curNav","notice");

		try{
			MessageText messageText = new MessageText();
			messageText.setMemberId(SessionContext.getUserId());
			messageText.setReadStatus(new Long(1));
			messageTextService.updateSelectivity(messageText);

			page = messageTextService.queryListByUserId(SessionContext.getUserId(),page);
			mv.addObject("page",page);
		}catch (Exception e){
			e.printStackTrace();
		}
		return mv;
	}

    /**
     * 删除消息
     */
    @RequestMapping("/delNotice")
    @ResponseBody
    public String delNotice(Long id){
        try{
            MessageText messageText = new MessageText();
            messageText.setId(id);
            messageText.setMemberId(SessionContext.getUserId());
            messageText.setStatus("0");
            messageTextService.updateSelectivity(messageText);
            return new JsonView(0).toString();//成功
        }catch (Exception e){
            e.printStackTrace();
            return new JsonView(1).toString();//异常
        }
    }
    /**
     * 全部设为已读
     */
    @RequestMapping("/delNoticeAll")
    public ModelAndView delNoticeAll(TailPage<MessageText> page){
        ModelAndView mv = new ModelAndView("user/notice");
        mv.addObject("curNav","notice");

        try{
            MessageText messageText = new MessageText();
            messageText.setMemberId(SessionContext.getUserId());
            messageText.setStatus("0");
            messageTextService.updateSelectivity(messageText);

            page = messageTextService.queryListByUserId(SessionContext.getUserId(),page);
            mv.addObject("page",page);
        }catch (Exception e){
            e.printStackTrace();
        }
        return mv;
    }
	
	/**
	 * 我的课程
	 */
	@RequestMapping("/course")
	public ModelAndView course(TailPage<UserCourseSectionDto> page){
		ModelAndView mv = new ModelAndView("user/course");
		mv.addObject("curNav","course");
		
		UserCourseSection queryEntity = new UserCourseSection();
		queryEntity.setUserId(SessionContext.getUserId());
		page = userCourseSectionService.queryPage(queryEntity, page);
		mv.addObject("page", page);
		return mv;
	}
	
	/**
	 * 我的收藏
	 */
	@RequestMapping("/collect")
	public ModelAndView collect(TailPage<UserCollections> page){
		ModelAndView mv = new ModelAndView("user/collect");
		mv.addObject("curNav","collect");
		UserCollections queryEntity = new UserCollections();
		queryEntity.setUserId(SessionContext.getUserId());
		page = userCollectionsService.queryPage(queryEntity, page);
		
		mv.addObject("page", page);
		return mv;
	}
	
	/**
	 * 信息
	 */
	@RequestMapping("/info")
	public ModelAndView info(){
		ModelAndView mv = new ModelAndView("user/info");
		mv.addObject("curNav","info");
		
		AuthUser authUser = authUserService.getById(SessionContext.getUserId());
		if(null != authUser && StringUtils.isNotEmpty(authUser.getHeader())){
			authUser.setHeader(QiniuStorage.getUrl(authUser.getHeader()));
		}
		mv.addObject("authUser",authUser);
		return mv;
	}
	/**
	 * 保存信息
	 */
	@RequestMapping("/saveInfo")
	@ResponseBody
	public String saveInfo(AuthUser authUser, @RequestParam MultipartFile pictureImg){
		try {
			authUser.setId(SessionContext.getUserId());
			if (null != pictureImg && pictureImg.getBytes().length > 0) {
				String key = QiniuStorage.uploadImage(pictureImg.getBytes());
				authUser.setHeader(key);
			}
			authUserService.updateSelectivity(authUser);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new JsonView().toString();
	}
	
	/**
	 * 密码
	 */
	@RequestMapping("/passwd")
	public ModelAndView passwd(){
		ModelAndView mv = new ModelAndView("user/passwd");
		mv.addObject("curNav","passwd");
		return mv;
	}
	
	/**
	 * 密码
	 */
	@RequestMapping("/savePasswd")
	@ResponseBody
	public String savePasswd(String oldPassword, String password, String rePassword){
		AuthUser currentUser = authUserService.getById(SessionContext.getUserId());
		if(null == currentUser){
			return JsonView.render(1,"用户不存在！");
		}
		oldPassword = EncryptUtil.encodedByMD5(oldPassword.trim());
		if(!oldPassword.equals(currentUser.getPassword())){
			return JsonView.render(1,"旧密码不正确！");
		}
		if(StringUtils.isEmpty(password.trim())){
			return JsonView.render(1,"新密码不能为空！");
		}
		if(!password.trim().equals(rePassword.trim())){
			return JsonView.render(1,"新密码与重复密码不一致！");
		}
		currentUser.setPassword(EncryptUtil.encodedByMD5(password));
		authUserService.updateSelectivity(currentUser);
		return new JsonView().toString();
	}
	
	/**
	 * 问答
	 */
	@RequestMapping("/qa")
	public ModelAndView qa(TailPage<CourseComment> page){
		ModelAndView mv = new ModelAndView("user/qa");
		mv.addObject("curNav","qa");
		
		CourseComment queryEntity = new CourseComment();
		queryEntity.setUsername(SessionContext.getUsername());
		page = courseCommentService.queryMyQAItemsPage(queryEntity, page);
		mv.addObject("page", page);
		
		return mv;
	}

	/**
	 * 支付
	 */
	@RequestMapping("/pay")
	public ModelAndView pay(){
		ModelAndView mv = new ModelAndView("user/paytest");
		mv.addObject("curNav","paytest");
		return mv;
	}
	/**
	 * 跳到支付页面
	 * 针对实时支付,即时付款
	 * @return
	 */
	@RequestMapping(value = "payAli", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String payAli(String money) {
	    return toPayAli(money,"青之巅CG课堂","余额充值");
    }

	public String toPayAli(String money,String title,String body) {
        //支付宝支付
        AliPayConfig alipayConfig = new AliPayConfig();

        AliPayConfigStorage aliPayConfigStorage = new AliPayConfigStorage();
        aliPayConfigStorage.setPid(alipayConfig.getPid());
        aliPayConfigStorage.setAppId(alipayConfig.getAppId());
        aliPayConfigStorage.setKeyPublic(alipayConfig.getAlipayPublicKey());
        aliPayConfigStorage.setKeyPrivate(alipayConfig.getPrivateKey());
        aliPayConfigStorage.setNotifyUrl(alipayConfig.getNotifyUrl());
        aliPayConfigStorage.setReturnUrl("http://www.qzdvfx.com/success.html");
        aliPayConfigStorage.setSignType(alipayConfig.getSignType());
        //	aliPayConfigStorage.setSeller("");
        aliPayConfigStorage.setInputCharset("utf-8");
        //是否为测试账号，沙箱环境
        aliPayConfigStorage.setTest(alipayConfig.getIsTest());
        //请求连接池配置
        HttpConfigStorage httpConfigStorage = new HttpConfigStorage();
        //最大连接数
        httpConfigStorage.setMaxTotal(20);
        //默认的每个路由的最大连接数
        httpConfigStorage.setDefaultMaxPerRoute(10);

        PayService service = new AliPayService(aliPayConfigStorage,httpConfigStorage);
        String orderId = NumberUtil.timeUinqueNumber()+"";
        PayOrders payOrders = new PayOrders();
        payOrders.setPayOrderNo(orderId);
        payOrders.setTotalAmount(Double.parseDouble(money));
        payOrders.setCreatDate(DateUtil.COMMON_FULL.getDateText(new Date()));

		PayOrder order = new PayOrder(title, body, new BigDecimal(Long.parseLong(money)) , orderId);
		//网页支付
		order.setTransactionType(AliTransactionType.DIRECT);
		//获取支付订单信息
		Map orderInfo = service.orderInfo(order);
		//组装成html表单信息
		return  service.buildRequest(orderInfo, MethodType.POST);
	}


	/**
	 * 支付测试  微信支付 支付宝支付 微信暂时还没有申请到账号
     * money 定单金额 精确到分 例如：0.01
     * type  调用的类型 1 支付宝 2 微信
     * title 定单标题
     * body  定单摘要
	 */
	@RequestMapping(value = "/paywx", produces = MediaType.TEXT_HTML_VALUE)
	@ResponseBody
	public String pay(String money,String type,String title,String body) {
		// http://localhost:8080/user/pay.html  // 模拟数据

        try{
            Long.parseLong(money);
        }catch (Exception e){
            return JsonView.render(1,"请输入正确的金额！");
        }

        String data = null;
		//获取扫码付的二维码
        try{
            BufferedImage image = null;
            if ("1".equals(type)){
//
            }else{
                //微信支付
                WxPayConfig wxPayConfig = new WxPayConfig();
                WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage();
                wxPayConfigStorage.setMchId(wxPayConfig.getMchId());//"合作者id（商户号）"
                wxPayConfigStorage.setAppid(wxPayConfig.getAppId());//"应用id"
        //        wxPayConfigStorage.setKeyPublic();//"转账公钥，转账时必填"
                wxPayConfigStorage.setSecretKey(wxPayConfig.getMchKey());//"密钥"
                wxPayConfigStorage.setNotifyUrl(wxPayConfig.getNotifyUrl());
        //        wxPayConfigStorage.setReturnUrl("同步回调地址");
                wxPayConfigStorage.setSignType(wxPayConfig.getSignType());//"签名方式"
                wxPayConfigStorage.setInputCharset("utf-8");

                        //https证书设置，退款必须 方式一
            /*
                HttpConfigStorage httpConfigStorage = new HttpConfigStorage();
                httpConfigStorage.setKeystore("证书信息串");
                httpConfigStorage.setStorePassword("证书密码");
                //是否为证书地址
                httpConfigStorage.setPath(false);
                PayService service = new WxPayService(wxPayConfigStorage, httpConfigStorage);
            */

                PayService service1 =  new WxPayService(wxPayConfigStorage);
                PayOrder payOrder1 = new PayOrder(title,
                        body,  new BigDecimal(Long.parseLong(money)) , NumberUtil.timeUinqueNumber()+"");
                /*-----------扫码付-------------------*/
                payOrder1.setTransactionType(WxTransactionType.NATIVE);
                //获取扫码付的二维码
                BufferedImage image1 = service1.genQrPay(payOrder1);
                        /*-----------/扫码付-------------------*/
                data = "<h1 class=\"price\">微信支付￥<span>"+money+"</span></h1>\n" +
                        "                        <div class=\"qrcode js-qrcode-img\">\n" +
                        "<img src='data:image/png;base64," + ImgUtil.BufferedImageToBase64(image) + "'/ >"+
                        "                        </div>\n" +
                        "                        <p>请使用微信扫描二维码进行支付</p>\n" ;
            }
        }catch (Exception e){
            e.printStackTrace();
            return JsonView.render(1,"获取支付二维码异常："+e.getMessage());
        }
        return JsonView.render(data);
//        return JsonView.render(0,"<img src='data:image/png;base64," + image + "'/ >");
	}

    /**
     * 我的钱包
     */
    @RequestMapping("/mymoney")
    public ModelAndView mymoney(){
        ModelAndView mv = new ModelAndView("user/mymoney");
        mv.addObject("curNav","mymoney");
        return mv;
    }
    /**
     * 获取优惠券
     */
    @RequestMapping("/getCoupon")
    @ResponseBody
    public String getCoupon(){
        JSONObject ob = new JSONObject();
        JSONObject obDate = new JSONObject();
        obDate.put("face_price","20");//面值
        obDate.put("full_reduced_price","100");//满减金额
        obDate.put("range_type","全部实战课程");//适用范围
        obDate.put("start_time","2016.05.02");//开始时间
        obDate.put("end_time","2016.12.10");//结束时间
        ob.put("result",0);
        ob.put("msg","成功");
        ob.put("date",obDate);

        return ob.toString();
    }



//    public static void main(String[] args) {
//        UserController s = new UserController();
//        String ss = s.paytest(null,null,null);
//        System.out.printf(ss);
//    }
	
}
